package com.ido.fastexcel;

import cn.idev.excel.EasyExcel;
import cn.idev.excel.ExcelWriter;
import cn.idev.excel.write.metadata.WriteSheet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * FastExcel工具类
 * Create by zoub
 * Date 2025/4/14 2:38 PM
 */
@Slf4j
public class ExcelUtils {

    /**
     * 普通导出
     * @param exportData
     * @param cls
     * @param fileName
     */
    public static void export(List<?> exportData, Class<?> cls, String fileName) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        response.setContentType("application/vnd.ms-excel");
//        response.setContentType("application/octet-stream"); // 设置内容类型
        response.setCharacterEncoding("utf-8");
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), cls).sheet(fileName)
//                    .registerConverter(new LongStringConverter()) // Long类型转String方式防止精度丢失
                    .doWrite(exportData);
        } catch (IOException e) {
            log.info("导出异常：{}", e.getMessage());
        }
    }


    /**
     * 多sheets数据导出
     * @param fileName
     */
    public static void export(List<ExcelSheet> sheets, String fileName) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        ExcelWriter excelWriter = null;
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            excelWriter = EasyExcel.write(response.getOutputStream()).build();
            WriteSheet writeSheet;
            for (ExcelSheet sheet : sheets) {
                // 构建sheet对象
                writeSheet = EasyExcel.writerSheet(sheet.getSheetName()).head(sheet.getCls()).build();
                // 写出sheet数据
                excelWriter.write(sheet.getData(), writeSheet);
            }
            excelWriter.finish();
        } catch (IOException e) {
            log.info("导出异常：{}", e.getMessage());
        }
    }

}
